<template>
  <BasicModal
    :width="460"
    :eight="220"
    v-bind="$attrs"
    @register="register"
    title="卡劵延期"
    :showFooter="true"
    okText="保存"
    @ok="onSave"
    :canFullscreen="false"
    :maskClosable="false"
    :centered="true"
    :destroyOnClose="true"
  >
    <div class="panel">
      <BasicForm @register="registerForm1"/>
    </div>
  </BasicModal>
</template>
<script setup>

/**
 * 卡延期
 */


import {reactive, ref} from 'vue';
import {BasicModal, useModalInner} from '@/components/Modal';
import {useMessage} from '@/hooks/web/useMessage';
import {BasicForm, useForm} from "@/components/Form";
import dayjs from "dayjs";
import {POST} from "@/api/http.js";

const orderHeader = ref([]);
const record = ref({});

const {createMessage} = useMessage();

const emit = defineEmits(['complete']);
const state = reactive({});

const [registerForm1, form1] = useForm({
  labelWidth: 100,
  baseColProps: {span: 24, style: {paddingRight: '36px'}},

  schemas: [
    {
      label: '原有效期',
      field: 'expireTime',
      required: false,
      component: 'Input',
      componentProps: {
        disabled: true,
      }
    },

    {
      show: false,
      label: '延期至',
      field: 'newActiveTimeDate',
      required: true,
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
        disabledDate: (currentDate) => dayjs(currentDate).isBefore(record.value.expireTime)
      }
    },
  ],
  showActionButtonGroup: false,
});

const [register, {closeModal}] =
  useModalInner(async ({
                         record: item
                       }) => {
    const {expireTime} = item;
    record.value = item;
    form1.updateSchema({
      field: 'newActiveTimeDate',
      show: true,
      componentProps: {
        defaultPickerValue: dayjs(expireTime).format('YYYY-MM-DD'),
      },
    });
    form1.setFieldsValue({expireTime: dayjs(expireTime).format("YYYY-MM-DD")});
  });

async function onSave() {
  await form1.validate();
  const formData = form1.getFieldsValue();

  const {cardNo, cardType, memberCode} = record.value;
  const {expireTime: activeTimeDate, newActiveTimeDate} = formData;

  await POST(`/card/updateUserCardActiveTime`, {
    cardNo, cardType, memberCode,
    activeTimeDate, newActiveTimeDate
  });

  createMessage.success('卡劵已延期');

  record.value.expireTime = newActiveTimeDate;
  emit('complete');

  closeModal();
}
</script>

<style lang="less" scoped>
.panel {
  padding: 8px 16px;
}
</style>
